import express, { Request, Response, NextFunction, Application } from 'express';
import cors from 'cors';
import path from 'path';
import dotenv from 'dotenv';

dotenv.config();

const app: Application = express();
const PORT: number = parseInt(process.env.PORT || '3000', 10);

// 中间件配置
app.use(cors());
app.use(express.json({ limit: '10mb' }));
app.use(express.urlencoded({ extended: true, limit: '10mb' }));

// 静态文件服务
app.use('/uploads', express.static(path.join(__dirname, 'uploads')));

// API路由
import authRoutes from './routes/auth';
import balanceRoutes from './routes/balance';
import depositRoutes from './routes/deposit';
import withdrawRoutes from './routes/withdraw';
import walletRoutes from './routes/wallet';
import stakingRoutes from './routes/staking';
import referralRoutes from './routes/referral';
import marketRoutes from './routes/market';
import tiersRoutes from './routes/tiers';
import userProfileRoutes from './routes/user-profile';

// 管理端路由
import adminAuthRoutes from './routes/admin/auth';
import adminTiersRoutes from './routes/admin/tiers';
import adminDepositRoutes from './routes/admin/deposit';
import adminWithdrawRoutes from './routes/admin/withdraw';
import adminUsersRoutes from './routes/admin/users';
import adminReferralRoutes from './routes/admin/referral';
import adminStakingRoutes from './routes/admin/staking';
import adminSettlementRoutes from './routes/admin/settlement';
import adminPartnerRoutes from './routes/admin/partner';
import adminTestRoutes from './routes/admin/test';
import { cronService } from './services/cronService';

// 用户端API
app.use('/api/auth', authRoutes);
app.use('/api/balance', balanceRoutes);
app.use('/api/deposit', depositRoutes);
app.use('/api/withdraw', withdrawRoutes);
app.use('/api/wallet', walletRoutes);
app.use('/api/staking', stakingRoutes);
app.use('/api/referral', referralRoutes);
app.use('/api/market', marketRoutes);
app.use('/api/tiers', tiersRoutes);
app.use('/api/user', userProfileRoutes);

// 管理端API
app.use('/api/admin/auth', adminAuthRoutes);
app.use('/api/admin/tiers', adminTiersRoutes);
app.use('/api/admin/referral', adminReferralRoutes); // 推荐路由要在users路由之前
app.use('/api/admin/deposit', adminDepositRoutes);
app.use('/api/admin/withdraw', adminWithdrawRoutes);
app.use('/api/admin/users', adminUsersRoutes);
app.use('/api/admin/staking', adminStakingRoutes);
app.use('/api/admin/settlement', adminSettlementRoutes);
app.use('/api/admin/partners', adminPartnerRoutes); // 合作伙伴管理路由
app.use('/api/admin/test', adminTestRoutes); // 测试路由

// 健康检查接口
app.get('/health', (req: Request, res: Response): void => {
  res.json({
    status: 'ok',
    timestamp: new Date().toISOString(),
    uptime: process.uptime()
  });
});

// 404处理
app.use('*', (req: Request, res: Response): void => {
  res.status(404).json({
    success: false,
    message: '요청한 인터페이스가 존재하지 않습니다.'
  });
});

// 全局错误处理中间件
app.use((err: Error, req: Request, res: Response, next: NextFunction): void => {
  console.error('서버 오류:', err);
  
  // 开发环境返回详细错误信息
  if (process.env.NODE_ENV === 'development') {
    res.status(500).json({
      success: false,
      message: err.message,
      stack: err.stack
    });
  } else {
    // 生产环境返回通用错误信息
    res.status(500).json({
      success: false,
      message: '서버 내부 오류가 발생했습니다.'
    });
  }
});

// 启动服务器
function startServer(): void {
  try {
    app.listen(PORT, (): void => {
      console.log('🚀 서버가 성공적으로 시작되었습니다.');
      console.log(`📍 서비스 주소: http://localhost:${PORT}`);
      console.log(`🌍 실행 환경: ${process.env.NODE_ENV || 'development'}`);
      console.log(`📊 헬스 체크: http://localhost:${PORT}/health`);

      // 启动定时任务
      console.log('🔄 정기 작업 서비스를 시작합니다...');
      cronService.init();
      console.log('✅ 정기 작업 서비스가 시작되었습니다.');
    });
  } catch (error) {
    console.error('❌ 서버 시작 실패:', error);
    process.exit(1);
  }
}

// 优雅关闭
process.on('SIGTERM', (): void => {
  console.log('SIGTERM 신호를 받아 서버를 종료하는 중입니다...');
  cronService.stopAllTasks();
  process.exit(0);
});

process.on('SIGINT', (): void => {
  console.log('SIGINT 신호를 받아 서버를 종료하는 중입니다...');
  cronService.stopAllTasks();
  process.exit(0);
});

startServer();

export default app;
